package com.kongmou.Springmvc.httpMessageConvert;

import java.io.IOException;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import com.kongmou.Springmvc.Entity.DemoObj;

public class MyMessageConvert extends AbstractHttpMessageConverter<DemoObj> {

	// 自定义类型
	public MyMessageConvert() {
		super(new MediaType("application", "x-wisely", Charset.forName("utf-8")));
	}

	// 声明只对DemoObj和其子类有效
	@Override
	protected boolean supports(Class<?> clazz) {
		return DemoObj.class.isAssignableFrom(clazz);
	}

	//
	@Override
	protected DemoObj readInternal(Class<? extends DemoObj> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {
		String tem = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("utf-8"));
		String[] temarry = tem.split("-");
		return new DemoObj(new Long(temarry[0]), temarry[1]);
	}

	@Override
	protected void writeInternal(DemoObj t, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		String out = "Hello " + t.getId() + t.getName();
		outputMessage.getBody().write(out.getBytes());
	}

}
